<template>
  <div class="image-uploader">
    <div class="image-list">
      <template v-if="images.length > 0">
        <div
          v-for="(image, index) in images"
          :key="image.id"
          class="image-item"
        >
          <el-image
            :src="image.imgUrl"
            fit="cover"
            :preview-src-list="[image.imgUrl]"
            hide-on-click-modal
          />
          <div class="image-label">{{ image.pictureName || label }}</div>
          <div class="delete-btn" @click="handleDelete(index)">
            <el-icon><Delete /></el-icon>
          </div>
        </div>
      </template>
      <div class="upload-item" v-if="images.length < 9">
        <el-upload
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="yuanhandleGoodImgUpload"
          :on-exceed="handleExceed"
          multiple
          :limit="9 - images.length"
          accept="image/*"
        >
          <el-icon class="upload-icon"><Plus /></el-icon>
          <div class="upload-text">{{ `还可上传${9 - images.length}张` }}</div>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import type { UploadUserFile as UploadFile } from "element-plus";
import { Delete, Plus } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";

interface ImageInfo {
  id: number;
  pictureName: string;
  imgUrl: string;
  pictureType: number;
  production_Batch: string;
}

const props = defineProps<{
  type: number;
  label: string;
  productionBatch: string;
}>();

const emit = defineEmits(["update:images", "change"]);

const images = ref<ImageInfo[]>([]);

// 监听图片列表变化
watch(
  images,
  (newImages) => {
    emit("update:images", newImages);
    emit("change", newImages);
  },
  { deep: true }
);

// 获取图片列表
const fetchImages = async () => {
  try {
    console.log("获取图片列表参数:", {
      batch: props.productionBatch,
      type: props.type,
    });

    const response = await axios.get(
      "https://localhost:7008/api/Img/GetPicture",
      {
        params: {
          production_Batch: props.productionBatch,
          pictureType: props.type,
        },
      }
    );

    console.log("获取图片列表响应:", response.data);

    if (response.data && response.data.code == 200) {
      const data = response.data.data || [];
      images.value = Array.isArray(data)
        ? data.filter((item: any) => {
            const isValid =
              item && item.imgUrl && item.pictureType == props.type;

            console.log("图片项检查:", {
              item,
              isValid,
              expectedType: props.type,
            });

            return isValid;
          })
        : [];

      console.log("筛选后的图片列表:", images.value);
    }
  } catch (error) {
    console.error(`获取类型 ${props.type} 的图片列表失败:`, error);
    ElMessage.error("获取图片列表失败");
  }
};

// 添加超出限制处理函数
const handleExceed = () => {
  ElMessage.warning(`最多只能上传9张图片`);
};

function yuanhandleGoodImgUpload(file: any) {
  // 检查当前图片数量
  if (images.value.length >= 9) {
    ElMessage.warning("已达到最大上传数量限制（9张）");
    return;
  }

  // 检查剩余可上传数量
  const remainingSlots = 9 - images.value.length;

  const formData = new FormData();
  formData.append("formFiles", file.raw);
  formData.append("ImgType", props.type.toString());
  formData.append("Batch", props.productionBatch);

  console.log("开始上传文件:", {
    fileName: file.raw.name,
    batch: props.productionBatch,
    type: props.type,
    remainingSlots,
  });

  // 第一步：上传文件到MinIO
  axios
    .post("https://localhost:7008/api/MinioImg/UploadFiles", formData)
    .then((res) => {
      console.log("MinIO上传响应:", res.data);

      // 检查返回的数据是否是数组
      if (res.data && Array.isArray(res.data)) {
        const imgUrls = res.data.filter(
          (url: string) => typeof url === "string" && url.startsWith("http")
        );

        if (imgUrls.length === 0) {
          console.error("MinIO上传成功但未返回有效URL");
          ElMessage.error("未获取到有效的图片URL");
          return;
        }

        console.log("获取到的图片URL:", imgUrls);

        // 第二步：创建图片记录
        const createPromises = imgUrls.map((imgUrl: string) => {
          const imgInfo = {
            pictureName: props.label,
            imgUrl: imgUrl,
            pictureType: props.type,
            production_Batch: props.productionBatch,
          };

          console.log("创建图片记录:", imgInfo);

          return axios.post(
            "https://localhost:7008/api/Img/CreatePicture",
            imgInfo
          );
        });

        return Promise.all(createPromises);
      } else {
        throw new Error("上传返回格式不正确");
      }
    })
    .then((createResults) => {
      if (Array.isArray(createResults) && createResults.length > 0) {
        console.log(
          "所有图片记录创建响应:",
          createResults.map((res) => res.data)
        );

        const allSuccess = createResults.every(
          (res) => res.data && res.data.code == 200
        );
        if (allSuccess) {
          ElMessage.success("上传成功");
          fetchImages(); // 刷新图片列表
        } else {
          const failedCount = createResults.filter(
            (res) => !res.data || res.data.code != 200
          ).length;
          ElMessage.warning(
            `部分图片上传失败 (${failedCount}/${createResults.length})`
          );
          fetchImages(); // 即使部分失败也刷新列表
        }
      }
    })
    .catch((error) => {
      console.error("上传过程出错:", error);
      ElMessage.error(error.response?.data?.msg || error.message || "上传失败");
    });
}

// 处理图片删除
const handleDelete = async (index: number) => {
  try {
    const image = images.value[index];
    if (!image) return;

    const response = await axios({
      url: "https://localhost:7008/api/Img/DeletePicture",
      method: "delete",
      params: {
        id: image.id,
        production_Batch: image.production_Batch,
        pictureType: image.pictureType,
      },
    });

    if (response.data.code === 200) {
      images.value.splice(index, 1);
      ElMessage.success("删除成功");
    } else {
      ElMessage.error(response.data.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败，请检查网络连接");
  }
};

onMounted(async () => {
  await fetchImages();
});
</script>

<style scoped>
.image-uploader {
  width: 100%;
  padding: 16px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.image-item {
  width: 160px;
  height: 160px;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

.image-item .el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.9);
  font-size: 12px;
  text-align: center;
  border-top: 1px solid #e4e7ed;
}

.delete-btn {
  position: absolute;
  top: 6px;
  right: 6px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s;
  z-index: 1;
}

.delete-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
  transform: scale(1.1);
}

.upload-item {
  width: 160px;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.upload-item:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.upload-icon {
  font-size: 24px;
  color: #8c939d;
  transition: all 0.3s;
}

.upload-item:hover .upload-icon {
  color: #409eff;
  transform: scale(1.1);
}

.upload-text {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 响应式设计 */
@media screen and (max-width: 1440px) {
  .image-item,
  .upload-item {
    width: 150px;
    height: 150px;
  }
}

@media screen and (max-width: 1200px) {
  .image-item,
  .upload-item {
    width: 140px;
    height: 140px;
  }
}
</style>
